<template>
  <!--visible  -->
  <a-modal
    v-model:visible="visible"
    :width="750"
    title="续费操作"
    centered
    :ok-button-props="{ loading: submitting }"
    :cancel-button-props="{ disabled: submitting }"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <!--   -->
    <a-spin :spinning="loading || caling">
      <template v-if="BW || BWYXB || CBYXB || DFTEH || WBTEH || CBTEH || HJBW || CiBao">
        <h3 class="title">订单信息：</h3>
        <a-descriptions class="renewal-desc">
          <a-descriptions-item label="产品">{{ data.productName }}</a-descriptions-item>
          <a-descriptions-item label="类型">续费</a-descriptions-item>
          <a-descriptions-item label="时间段">{{ data.onLinePeriod }}</a-descriptions-item>
          <a-descriptions-item label="版本">{{ BwVersionTypeKeyMap[data.versionType] }}</a-descriptions-item>
          <a-descriptions-item label="创意配图">{{ data.hasCreatePic ? '有' : '无' }}</a-descriptions-item>
          <a-descriptions-item label="360标王">{{ has360 ? '有' : '无' }}</a-descriptions-item>
        </a-descriptions>
        <div @click="visibleitem = !visibleitem" v-if="!CBTEH && !DFTEH && !CBYXB && !CiBao && checks && !HJBW">
          <h3 class="title">订单地区:</h3>
          <p class="ellipsis hover-text" v-if="Array.isArray(serviceAreasitem) && serviceAreasitem.length === 0">
            {{ props.data.areas }}
          </p>

          <p class="ellipsis hover-text" v-else>
            {{ serviceAreasitem }}
          </p>
        </div>
        <div v-else>
          <h3 class="title">订单地区:</h3>
          <p class="ellipsis hover-text">
            {{ props.data.areas }}
          </p>
        </div>
        <h3 class="title">关键词：</h3>
        <!-- v-if="" -->
        <a-button v-if="!CBTEH && !DFTEH && !CBYXB && !CiBao && checks && !HJBW" @click="addNewKeyword">新增</a-button>
        <div class="keyword-table">
          <a-table
            :pagination="false"
            row-key="frontKey"
            :columns="columns"
            :loading="loading"
            :data-source="orderKeyword"
          >
            <template #bodyCell="{ column, record }">
              <!-- <template v-if="column.key === 'name'">
                <a-input  
                  :value="record.name"
                  @update:value="(value) => handleInputChange(record, value)"
                  @blur="() => handleSaveEdit(record)"
                  placeholder="请输入关键词"
                  allow-clear
                />
              </template> -->
              <template v-if="column.key === 'name' && checks">
                <a-input
                  :value="record.name"
                  @update:value="(value) => handleInputChange(record, value)"
                  @blur="() => handleSaveEdit(record)"
                  placeholder="请输入关键词"
                  allow-clear
                />
              </template>

              <template v-if="column.key === 'caozuo'">
                <a-button v-if="!CBTEH && !DFTEH && !CBYXB && !CiBao && checks" @click="deleteKeyword(record)"
                  >删除</a-button
                >
              </template>
            </template>
          </a-table>
        </div>
        <div v-if="!CBTEH && !DFTEH && !CBYXB && !CiBao">
          <h3 class="title-two">续费时长：</h3>
          <div>
            <a-radio-group
              :value="data.comboPriceName"
              :options="comboPriceOptions"
              @change="(emit('on-change', $event.target.value), (renewMarketPrices = 0))"
            />
          </div>
        </div>
      </template>
      <!-- <template>
        <h3>订单地区1</h3>
        <h3 class="title">订单信息：</h3>
        <a-descriptions class="renewal-desc">
          <a-descriptions-item label="产品">{{ data.productName }}</a-descriptions-item>
          <a-descriptions-item label="类型">续费</a-descriptions-item>
          <a-descriptions-item label="时间段">7*24小时</a-descriptions-item>
          <a-descriptions-item label="购买套餐">{{ data.comboName }}</a-descriptions-item>
          <a-descriptions-item label="订单时长">{{ data.comboPriceName }}</a-descriptions-item>
          <a-descriptions-item label="市场价">¥{{ data.comboPrice }}</a-descriptions-item>
        </a-descriptions>
        <h3 class="title">关键词：</h3>
        <div class="keyword-table">
          <a-table
            :pagination="false"
            row-key="frontKey"
            :columns="columns"
            :loading="loading"
            :data-source="orderKeyword"
          >
          </a-table>
        </div>
      </template> -->

      <h3 class="title-two">续费价：</h3>
      <div style="display: flex; align-items: center; justify-content: space-between">
        <div style="display: flex; align-items: center">
          <div>
            <div v-if="!loadingsd">
              <a-statistic :precision="2" class="price" prefix="¥" :value="renewMarketPrices" />
            </div>
            <div v-else>
              <a-spin />
            </div>
          </div>
          <a-button style="margin-left: 20px" @click="prices">点击获取价格</a-button>
        </div>
        <a-button @click="chongzhishu"> 重置 </a-button>
      </div>
      <div style="display: flex; align-items: center">
        <p style="color: red; margin-top: 15px; font-size: 15px" v-if="noteitem">{{ noteitem }}</p>
        <p v-if="oldPrices" style="margin-top: 16px; margin-left: 20px">
          原价：<span style="text-decoration: line-through">{{ oldPrices }}</span>
        </p>
      </div>
    </a-spin>

    <template v-slot:footer>
      <!-- 根据权限显示或隐藏确定按钮 
       [] 
      -->

      <a-button @click="handleCancel" :loading="submitting">取消</a-button>
      <a-button
        style="background-color: red; color: white"
        v-if="mainStore.userInfo.type !== 1"
        @click="handleSubmit"
        :loading="submitting"
        >确定</a-button
      >
    </template>
  </a-modal>
  <BwArea
    :selected="data.areas"
    @change="handleAreaChange"
    :loading="loadingsd"
    v-model:show="visibleitem"
    ref="BwAreaRef"
  />
</template>

<script lang="ts" setup>
import BwArea from '@/views/price-sheet/components/BwArea.vue'
import { computed, ref, watch } from 'vue'
import { useVModel } from '@vueuse/core'
import { BwVersionTypeKeyMap } from '@/views/price-sheet/interface'
import { useCategory } from '@/hooks/useCategotry'
import { TableProps, message } from 'ant-design-vue'
import { KeywordData } from '@/services/order/getOrderKeyword'
import { ComboPriceNameEnum } from '@/core/enums/name'
import { PlatformKeyMap } from '@/core/mapper/platform'
import { PlatformEnum, ProductEnum } from '@/core/enums/platform'
import { ChannelTypeEnum } from '@/core/enums/type'
import getRenewPrice from '@/services/account-management/getRenewPrice'
import getCbRenewPrice from '@/services/account-management/getCbRenewPrice'
import { AuthEnum } from '@/core/enums/auth'
import { useMainStore } from '@/store/useMainStore'
const visibleitem = ref(false)
interface Props {
  show: boolean
  submitting: boolean
  loading: boolean
  data: Partial<any>
  caling: boolean
  orderId: number
  orderKeyword: KeywordData[]
}
const checks = ref(false)
const mainStore = useMainStore()

const { ADMIN, AGENT, AGENT_BOSS, SALES, OPERATION, CUSTOMER } = AuthEnum
// const emits = defineEmits(['update-data'])
const visiblesitsusd = ref(false)
const serviceAreasitem = ref([])
const serviceAreasitems = ref([])
// const serviceAreasitems = ref(props.data.areas)
function handleAreaChange(cityMap: Record<string, string[]>) {
  console.log('cityMap', cityMap)
  renewMarketPrices.value = 0
  // serviceAreasitems.value = props.data.areas == serviceAreasitem.value ? props.data.areas : cityMap
  // serviceAreasitem.value = cityMap
  serviceAreasitem.value = cityMap
  console.log('cityMapssss', serviceAreasitem.value)
}

interface Emits {
  (e: 'on-submit'): void
  (e: 'on-reset'): void
  (e: 'update:show'): void
  (e: 'update:data'): void
  (e: 'on-change', v: string): void
  (e: 'update:orderKeyword', keywords: KeywordData[]): void
  // (e: 'update-data', data1: string[], data2: string[]): void
}

// 重置数据
const chongzhishu = () => {
  // 重置价格
  renewMarketPrices.value = 0
  // 重置地区选择
  serviceAreasitem.value = []
  // 重置关键词到初始状态
  emit('update:orderKeyword', [...props.orderKeyword])
  // 触发父组件的重置事件
  emit('on-reset')
  checks.value = false
  noteitem.value = ''
  oldPrices.value = 0
}

// const addNewKeyword = () => {
//   renewMarketPrices.value = 0
//   const newKeyword = {
//     frontKey: Date.now().toString(),
//     name: '',
//     key: Date.now().toString(),
//     clientType: props.orderKeyword[0].clientType
//   }
//   emit('update:orderKeyword', [...props.orderKeyword, newKeyword])
// }
const addNewKeyword = () => {
  renewMarketPrices.value = 0
  const newKeyword = {
    frontKey: Date.now().toString(), // Ensure unique key
    name: '',
    key: Date.now().toString(), // Ensure unique key
    clientType: props.orderKeyword[0]?.clientType || '' // Handle case where orderKeyword might be empty
  }
  emit('update:orderKeyword', [...props.orderKeyword, newKeyword])
}

const props = withDefaults(defineProps<Props>(), {
  show: false,
  submitting: false,
  loading: false,
  caling: false,
  orderId: 0,
  orderKeyword: () => []
})
// const handleInputChange = (frontKey: string, value: string) => {
//   renewMarketPrices.value = 0
//   const updatedKeywords = props.orderKeyword.map((keyword) => {
//     if (keyword.frontKey === frontKey) {
//       // Use frontKey for comparison
//       return { ...keyword, name: value }
//     }
//     return keyword
//   })
//   emit('update:orderKeyword', updatedKeywords)
// }

const handleInputChange = (frontKey: string, value: string) => {
  renewMarketPrices.value = 0
  const updatedKeywords = props.orderKeyword.map((keyword) => {
    if (keyword.frontKey === frontKey.frontKey && keyword.id === frontKey.id) {
      return { ...keyword, name: value }
    }
    return keyword
  })
  // console.log('修改关键词', updatedKeywords, props.orderKeyword)

  emit('update:orderKeyword', updatedKeywords)
}

const handleSaveEdit = (record: KeywordData) => {
  // 这里可以添加保存到后端的逻辑，如果需要的话
  console.log('保存修改', record)
}
// const deleteKeyword = (record: KeywordData) => {
//   const updatedKeywords = props.orderKeyword.filter((keyword) => keyword.frontKey !== frontKey.frontKey) // Use frontKey for comparison
//   emit('update:orderKeyword', updatedKeywords)
// }
// const deleteKeyword = (record: KeywordData) => {
//   // console.log('删除关键词', record, '5', props.orderKeyword)
//   // renewMarketPrices.value = 0
//   const updatedKeywords = props.orderKeyword.filter((keyword) => keyword.id !== record.id)
//   // console.log('删除关键词', updatedKeywords.value, updatedKeywords)
//   emit('update:orderKeyword', updatedKeywords)
// }

const deleteKeyword = (record: KeywordData) => {
  console.log('删除关键词', record)
  const index = props.orderKeyword.findIndex((keyword) => keyword.id === record.id)
  if (index !== -1) {
    const updatedKeywords = [...props.orderKeyword]
    updatedKeywords.splice(index, 1)
    emit('update:orderKeyword', updatedKeywords)
  }
}
const [, getRenewPriceFn, loadingsd] = getRenewPrice()
const [, getCbRenewPriceFn, loadingsdds] = getCbRenewPrice()

const renewMarketPrices = ref(0)
const noteitem = ref('')
const oldPrices = ref(0)
const prices = async () => {
  //
  // visiblesits.value = true
  const keywordNames = props.orderKeyword.map((item) => item.name)
  // const stringArray = [props.data.areas]
  // serviceAreasitem.value
  // 添加验证逻辑
  // console.log('查询价格')
  if (
    props.data.productId == 2 ||
    props.data.productId == 6 ||
    props.data.productId == 7 ||
    props.data.productId == 10
  ) {
    let [err, res] = await getCbRenewPriceFn({
      words: props.orderKeyword,
      orderId: props.orderId
    })

    if (!err && res.data.code == 0) {
      console.log('ress', res.data.data)

      let ze = /.*与您的渠道经理沟通.*/
      if (ze.test(res.data.data.note)) {
        console.log('有沟通')
        // checks.value = true
      } else {
        console.log('没有沟通')
      }

      oldPrices.value = res.data.data.oldPrice
      noteitem.value = res.data.data.note
      renewMarketPrices.value = Math.round(res.data.data.comboPrice * res.data.data.premiumRatio)
      localStorage.setItem('renewMarketPriceses', JSON.stringify(res.data.data))
    }
  } else {
    var stringArray = []
    if (Array.isArray(serviceAreasitem.value) && serviceAreasitem.value.length === 0) {
      stringArray = stringArray = props.data.areas.split(',').filter((area) => area.trim())
    } else {
      stringArray = serviceAreasitem.value
    }
    const allCities = [
      '巢湖',
      '蚌埠',
      '安庆',
      '滁州',
      '亳州',
      '合肥',
      '淮北',
      '黄山',
      '阜阳',
      '马鞍山',
      '六安',
      '芜湖',
      '铜陵',
      '宿州',
      '宣城',
      '淮南',
      '池州',
      '定西',
      '甘南',
      '兰州',
      '酒泉',
      '陇南',
      '临夏',
      '平凉',
      '庆阳',
      '天水',
      '张掖',
      '金昌',
      '白银',
      '嘉峪关',
      '武威',
      '福州',
      '南平',
      '龙岩',
      '三明',
      '莆田',
      '泉州',
      '宁德',
      '厦门',
      '漳州',
      '安阳',
      '洛阳',
      '焦作',
      '漯河',
      '济源',
      '平顶山',
      '濮阳',
      '三门峡',
      '南阳',
      '商丘',
      '新乡',
      '许昌',
      '信阳',
      '郑州',
      '开封',
      '鹤壁',
      '周口',
      '驻马店',
      '黄石',
      '鄂州',
      '黄冈',
      '荆州',
      '荆门',
      '随州',
      '潜江',
      '武汉',
      '孝感',
      '咸宁',
      '仙桃',
      '天门',
      '襄阳',
      '十堰',
      '宜昌',
      '恩施',
      '神农架',
      '长沙',
      '常德',
      '衡阳',
      '怀化',
      '娄底',
      '邵阳',
      '湘潭',
      '株洲',
      '岳阳',
      '张家界',
      '益阳',
      '郴州',
      '永州',
      '湘西',
      '潮州',
      '河源',
      '东莞',
      '佛山',
      '惠州',
      '江门',
      '茂名',
      '揭阳',
      '深圳',
      '汕头',
      '韶关',
      '汕尾',
      '清远',
      '阳江',
      '广州',
      '珠海',
      '梅州',
      '湛江',
      '肇庆',
      '云浮',
      '中山',
      '北海',
      '百色',
      '崇左',
      '桂林',
      '贵港',
      '贺州',
      '河池',
      '南宁',
      '柳州',
      '来宾',
      '梧州',
      '玉林',
      '防城港',
      '钦州',
      '儋州',
      '澄迈',
      '定安',
      '白沙',
      '保亭',
      '昌江',
      '海口',
      '东方',
      '临高',
      '乐东',
      '陵水',
      '三亚',
      '琼海',
      '万宁',
      '五指山',
      '屯昌',
      '文昌',
      '琼中',
      '安顺',
      '毕节',
      '贵阳',
      '六盘水',
      '铜仁',
      '遵义',
      '黔东南',
      '黔南',
      '黔西南',
      '常州',
      '淮安',
      '南京',
      '连云港',
      '宿迁',
      '盐城',
      '扬州',
      '泰州',
      '无锡',
      '苏州',
      '徐州',
      '南通',
      '镇江',
      '赣州',
      '抚州',
      '景德镇',
      '九江',
      '吉安',
      '萍乡',
      '新余',
      '宜春',
      '南昌',
      '鹰潭',
      '上饶',
      '长春',
      '白城',
      '辽源',
      '吉林',
      '松原',
      '通化',
      '四平',
      '白山',
      '延边',
      '大同',
      '晋城',
      '晋中',
      '临汾',
      '吕梁',
      '朔州',
      '太原',
      '阳泉',
      '忻州',
      '长治',
      '运城',
      '包头',
      '赤峰',
      '巴彦淖尔',
      '呼和浩特',
      '鄂尔多斯',
      '呼伦贝尔',
      '乌海',
      '通辽',
      '阿拉善',
      '乌兰察布',
      '锡林郭勒',
      '兴安',
      '德州',
      '滨州',
      '东营',
      '菏泽',
      '济南',
      '济宁',
      '莱芜',
      '临沂',
      '聊城',
      '青岛',
      '日照',
      '潍坊',
      '威海',
      '泰安',
      '淄博',
      '枣庄',
      '烟台',
      '德阳',
      '达州',
      '巴中',
      '阿坝',
      '广元',
      '广安',
      '泸州',
      '乐山',
      '南充',
      '眉山',
      '攀枝花',
      '遂宁',
      '内江',
      '雅安',
      '自贡',
      '宜宾',
      '成都',
      '绵阳',
      '资阳',
      '甘孜',
      '凉山',
      '宝鸡',
      '安康',
      '汉中',
      '商洛',
      '西安',
      '铜川',
      '渭南',
      '延安',
      '榆林',
      '咸阳',
      '海东',
      '西宁',
      '果洛',
      '海北',
      '海西',
      '黄南',
      '玉树',
      '海南',
      '日喀则',
      '林芝',
      '山南',
      '阿里',
      '拉萨',
      '那曲',
      '昌都',
      '阿拉尔',
      '阿克苏',
      '巴音郭楞',
      '博尔塔拉',
      '昌吉',
      '克拉玛依',
      '哈密',
      '和田',
      '喀什',
      '石河子',
      '阿勒泰',
      '乌鲁木齐',
      '图木舒克',
      '五家渠',
      '吐鲁番',
      '塔城',
      '克孜勒苏',
      '伊犁',
      '保定',
      '承德',
      '沧州',
      '衡水',
      '秦皇岛',
      '邢台',
      '石家庄',
      '唐山',
      '邯郸',
      '张家口',
      '廊坊',
      '大连',
      '鞍山',
      '本溪',
      '丹东',
      '朝阳',
      '抚顺',
      '葫芦岛',
      '阜新',
      '锦州',
      '辽阳',
      '沈阳',
      '盘锦',
      '铁岭',
      '营口',
      '大庆',
      '大兴安岭',
      '哈尔滨',
      '鹤岗',
      '佳木斯',
      '黑河',
      '鸡西',
      '牡丹江',
      '齐齐哈尔',
      '双鸭山',
      '七台河',
      '绥化',
      '伊春',
      '杭州',
      '湖州',
      '嘉兴',
      '金华',
      '丽水',
      '绍兴',
      '衢州',
      '温州',
      '宁波',
      '舟山',
      '台州',
      '保山',
      '楚雄',
      '大理',
      '迪庆',
      '昆明',
      '临沧',
      '丽江',
      '曲靖',
      '普洱',
      '怒江',
      '文山',
      '玉溪',
      '昭通',
      '德宏',
      '红河',
      '西双版纳',
      '固原',
      '石嘴山',
      '吴忠',
      '银川',
      '中卫',
      '重庆',
      '上海',
      '北京',
      '天津'
    ]

    // 校验stringArray是否包含了全国所有的市
    const isAllCitiesIncluded = allCities.every((city) => stringArray.includes(city))

    // 如果包含了全国所有的市，那么只保留一个“全国”的值
    if (isAllCitiesIncluded) {
      stringArray = ['全国']
    }
    const resultString = stringArray.join()
    const [err, res] = await getRenewPriceFn({
      serviceAreas: stringArray,
      priceAskWords: keywordNames,
      orderId: props.orderId,
      comboPriceName: props.data.comboPriceName
    })
    console.log('查询价格6', res)
    if (!err) {
      let ze = /.*与您的渠道经理沟通.*/
      if (ze.test(res.data.data.note)) {
        console.log('有沟通')
        checks.value = true
      } else {
        console.log('没有沟通')
      }

      oldPrices.value = res.data.data.oldPrice
      renewMarketPrices.value = res.data.data.renewMarketPrice
      noteitem.value = res.data.data.note
      // 存入本地
      localStorage.setItem('renewMarketPrices', JSON.stringify(res.data))
      localStorage.setItem('stringArray', JSON.stringify(resultString))
      if (res.data.data.failtureCode == -1) {
        message.error(res.data.data.msg)
      }
      visiblesitsusd.value = true
    } else {
      // message.error(err.message)
    }
  }
}

const emit = defineEmits<Emits>()
const visible = useVModel(props, 'show', emit)
const { MONTH, QUARTET, HALF_YEAR, YEAR, TwoYEAR } = ComboPriceNameEnum
const productId = computed(() => {
  return props.data.productId || ProductEnum.BW
})
watch(
  () => visible.value,
  (newValue) => {
    if (!newValue) {
      // When modal is closed
      serviceAreasitem.value = [] // Reset to empty array
      noteitem.value = ''
      checks.value = false
    }
  }
)
const { BW, BWYXB, CiBao, CBYXB, DFTEH, WBTEH, CBTEH, HJBW } = useCategory(productId)

const columns = computed<TableProps['columns']>(() => {
  return [
    {
      title: '关键词',
      dataIndex: 'name',
      key: 'name'
    },
    {
      title: '端口',
      dataIndex: 'clientType',
      key: 'clientType',
      filters: [
        { text: PlatformKeyMap[PlatformEnum.PC], value: PlatformEnum.PC },
        { text: PlatformKeyMap[PlatformEnum.MOBILE], value: PlatformEnum.MOBILE }
      ],
      onFilter: (value: any, record: KeywordData) => record.clientType === value,
      customRender: ({ text }: { text: PlatformEnum }) => {
        return PlatformKeyMap[text]
      }
    },
    {
      title: '操作',
      dataIndex: 'caozuo',
      key: 'caozuo'
    }
  ]
})

const comboPriceOptions = [
  {
    label: MONTH,
    value: MONTH
  },
  {
    label: QUARTET,
    value: QUARTET
  },
  {
    label: HALF_YEAR,
    value: HALF_YEAR
  },
  {
    label: YEAR,
    value: YEAR
  }
]

// ,
//   {
//     label: TwoYEAR,
//     value: TwoYEAR
//   }
const has360 = computed(() => {
  if (props.data.productId === ProductEnum.BW || props.data.productId === ProductEnum.BWYXB) {
    return props.data.channelPrices?.some((channel) => channel.channelType === ChannelTypeEnum.QiHu360)
  } else {
    return false
  }
})
watch(
  () => props.loading,
  (newValue, oldValue) => {
    // console.log('', newValue)
    if (oldValue === true && newValue === false) {
      // Reset price when loading finishes
      renewMarketPrices.value = 0
    }
  }
)
watch(
  () => loadingsd.value,
  (newValue, oldValue) => {
    if (oldValue === true && newValue === false) {
      /*
      
      */
      renewMarketPrices.value = 0
    }
  }
)

function handleSubmit() {
  if (renewMarketPrices.value === 0) {
    message.error('请先查询价格')
  } else {
    emit('on-submit')
  }
}

function handleCancel() {
  visible.value = false
}
</script>

<script lang="ts">
export default {
  name: 'OrderRenewal'
}
</script>

<style lang="scss" scoped>
.title {
  margin-bottom: 20px;
  line-height: 1;
  font-weight: bolder;
}

.title-two {
  margin-top: 20px;
  margin-bottom: 20px;
  line-height: 1;
  font-weight: bolder;
}

.hover-text {
  transition: color 0.3s ease;
  cursor: pointer; // 添加鼠标指针效果

  &:hover {
    color: red;
  }
}

.ellipsis {
  width: 200px;
  font-size: 17px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.price {
  ::v-deep(.ant-statistic-content) {
    color: #ff4d4f;
    line-height: 1;
  }
}

.line {
  margin-top: 4px;
}

.keyword-table {
  max-height: 300px;
  overflow: auto;
}
</style>
